<?php
namespace app\web\controller;

use app\model\Fee; 
use app\model\Theme; 
use app\model\Order; 

class Comm extends Base
{
    public function Comm()
    {
global $_G, $_P;
if (strstr($_SERVER['HTTP_HOST'],".y.yixuan.net")!==false){
    return_msg('请不要使用管理网址操作!');
}
$system = $_G['system'];
$_G['page']['title'] = '分销管理 - ' . $system['title'];
//load_func('tpl');
$GLOBALS['frames'] = array();
$themeid = intval($_P['themeid']);
if($themeid <= 0){
    $themeid = Theme::getDefaultThemenew();
}
$theme = Theme::getThemeById($themeid);
$config =   Theme::getConfig($themeid);
if(empty($themeid)){
    return_msg('还没有创建活动,请联系管理员');
}
$id = intval($_P['id']);
$do = 'comm';
$op = !empty($_P['op']) ? $_P['op'] : 'display';
$url = createWebUrl($do,array('op' => 'display','themeid'=>$themeid));


if($op == 'edit') {
    
    if($id > 0) {
        $item = db_find('SELECT * FROM ' . tablename(t_fans) . ' 
                WHERE themeid = :themeid AND id = :id', array( ':themeid' => $themeid,':id' => $id));
        if(empty($item)) {
            return_tips('该用户不存在或已删除', $url, 'success');
        }
    }
    
    $url = createWebUrl($do,array('op' => 'edit','themeid'=>$themeid,'id'=>$id));

    $commcountzs = db_fetchcolumn ( "SELECT COUNT(*) FROM " . tablename (t_comm) . " 
                                     WHERE themeid = " . $themeid . " and openid = '". $item['openid']."' and status  = 1") ;

    $feesumzs = db_fetchcolumn ( "SELECT sum(fee) FROM " . tablename (t_comm) . 
                                    " WHERE themeid = " . $themeid . " and openid = '" . $item['openid'] ."' and status  = 1");

    $tuijianzs = db_fetchcolumn ( "SELECT COUNT(*) FROM " . tablename (t_record) . 
                                    " WHERE themeid = " . $themeid . " and fromuid = '" . $item['uid'] ."' and status > 0");

    $responsumzs = db_fetchcolumn ( "SELECT COUNT(*) FROM " . tablename (t_scan) . 
                                    " WHERE themeid = " . $themeid . " and fromuid = '" . $item['uid'] ."'");

    if ($system['fanpai'] == 1) {
        $pm = array(":themeid"=>$themeid,":openid"=>$item['openid']);
        $yichou = db_fetchcolumn("SELECT COUNT(*)  FROM ".tablename(t_fanpaichoujiang)."
        WHERE themeid = :themeid and openid = :openid",$pm);
    }

    if(checksubmit('submit')) {
        $avatar = tomedia($_P['avatar']);

        $commcountxuni = intval($_P['commcountxuni']);
        $feesumxuni = floatval($_P['feesumxuni']);
        $feesum = $feesumzs + $feesumxuni;
        $commcount = $commcountzs + $commcountxuni;

        $responsumxuni = intval($_P['responsumxuni']);
        $tuijianxuni = intval($_P['tuijianxuni']);
        $tuijian = $tuijianzs + $tuijianxuni;
        $responsum = $responsumzs + $responsumxuni;
        if ($system['fanpai']==1){
            if (intval($_P['jihui']) > $config['fanpailimit']) {
                return_tips('保存失败，抽奖机会最多为'.$config['fanpailimit'].'次',$url , 'suc cess');
            }
            $jihui = intval($_P['jihui']);
        }else{
            $jihui = $item['jihui'];
        }
        $data = array(
                'username' => trim($_P['username']),
                'nickname' => trim($_P['nickname']),
                'mobile' => trim($_P['mobile']),
                'avatar' => $avatar,
                'feesum' => $feesum,
                'commcount' => $commcount,
                'feesumxuni' => $feesumxuni,
                'commcountxuni' => $commcountxuni,
                'tuijian' => $tuijian,
                'responsum' => $responsum,
                'tuijianxuni' => $tuijianxuni,
                'jihui' => $jihui,
                'responsumxuni' => $responsumxuni,
            );
        db_update(t_fans, $data, array( 'id' => $_P['id']));
        
        return_tips('更新成功',$url , 'suc cess');
    }
}
if($op == 'update') {
    $commlist = db_select('SELECT * FROM ' . tablename(t_comm) . ' 
                WHERE themeid = :themeid and status  = 1 group by uid', array(  ':themeid' => $themeid));
    foreach ($commlist as $index => $item) {

        $commcountzs = db_fetchcolumn ( "SELECT COUNT(*) FROM " . tablename (t_comm) . " 
                                         WHERE themeid = " . $themeid . " and openid = '". $item['openid']."' and status  = 1") ;

        $feesumzs = db_fetchcolumn ( "SELECT sum(fee) FROM " . tablename (t_comm) . 
                                        " WHERE themeid = " . $themeid . " and openid = '" . $item['openid'] ."' and status  = 1");
        $fansv = db_find('SELECT * FROM ' . tablename(t_fans) . ' 
                WHERE themeid = :themeid AND uid = :uid', array( ':themeid' => $themeid,':uid' => $item['uid']));

        $data = array(
                'feesum' =>  $feesumzs + $fansv['feesumxuni'],
                'commcount' => $commcountzs + $fansv['commcountxuni'],
            );
        db_update(t_fans, $data, array( 'id' => $fansv['id']));


    }
    return_tips('更新成功',$url. '&status=-2', 'success');
}
if($op == 'display'){
    $themelist = Theme::getAllTheme();
    $sql = 'SELECT w.*,t.name as teamname,s.name as companyname FROM ' . tablename(t_worker) . " as w 
            left join " . tablename ( t_team ) . " as t on w.team = t.id
            left join " . tablename ( t_shangjia ) . " as s on w.company = s.id
            WHERE w.themeid = :themeid
            ORDER BY company,team,uid  ";
    $wlist = db_select($sql, array(":themeid"=>$themeid));
     
    if (empty($_P['createtime']['start'])){
		$starttime =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
		$starttime =  strtotime(date('Y-m-d 00:00:00',$starttime));
	}else{
		$starttime =  strtotime($_P['createtime']['start']);
	}
    $endtime = empty($_P['createtime']['end']) ? strtotime(date('Y-m-d 23:59:59',TIMESTAMP)): strtotime($_P['createtime']['end']);

	$condition = '1=1 ';
    $condition.= " and cm.addtime > '{$starttime}' and cm.addtime <= '{$endtime}' ";
    if(!isset($_P['status'])){
        $status = -1;
    }else{
        $status = intval($_P['status']);
    }
    if($status >= 0){
        $condition.= " and cm.status = '{$status}'  ";
    }
    $workerid = $_P['workerid'];
    if(!empty($workerid)){
        $condition.= " and cm.uid = '{$workerid}'  ";
    }

    if(!isset($_P['type'])){
        $type = -1;
    }else{
        $type = intval($_P['type']);
    }
    if($type >= 0){
        $condition.= " and cm.type = '{$type}'  ";
    }

    $condition .= ' and cm.themeid = ' . $themeid;


    //批量补发
    if ($_P['submit_updatecomm']==2){
        $sql = "UPDATE ".tablename(t_comm)." as cm SET cm.msg = null WHERE {$condition} and cm.status = 0 and cm.msg ='等待管理员发红包'";
        db_query($sql);
        return_tips ( '操作成功，系统将在短时间内发放【符合搜索条件的】【等待管理员发红包】的红包！', referer (), 'success' );
    }

    $keyword = trim($_P['keyword']);
    if(!empty($keyword)){
        if (intval($keyword)>0 && strlen($_P['keyword'])!=11){
            $condition.= " and cm.uid = " . intval($keyword);
        }else{
            $condition.= " and (f.nickname like '%{$keyword}%' or f.username like '%{$keyword}%' or f.mobile like '%{$keyword}%' or d.username like '%{$keyword}%'  )";
        }
    }
	
	$pageNumber = max ( 1, intval ( $_P['page'] ) );
    if ($theme['endtime']<strtotime("-90 day")) {
        if ($pageNumber>1 && $_G['username']!=='benben') {
            return_msg('活动结束超3个月,无法查看');
        }
        $pageSize = 20;
    }elseif ($theme['endtime']<strtotime("-30 day")) {
        if ($pageNumber>1 && $_G['username']!=='benben' && $_G['username']!=='caiwu' && $_G['username']!=='chuna') {
            return_msg('活动结束超1个月,无法查看');
        }
        $pageSize = 20;
    }else{
		$pageSize = 50;
	}


	$sql = "SELECT cm.*,f.nickname,f.avatar,f.username as user ,f.mobile,d.username FROM ".tablename(t_comm)." as cm
								left join ".tablename(t_record)." as d on d.id = cm.recordid
										left join ".tablename(t_fans)." as f on f.openid = cm.openid and f.themeid = cm.themeid
									WHERE {$condition} order by cm.id desc
											 LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
	$list = db_select ( $sql);
	$total = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename (t_comm) . " as cm left join ".tablename(t_record)." as d on d.id = cm.recordid
                                        left join ".tablename(t_fans)." as f on f.openid = cm.openid and f.themeid = cm.themeid 
                                        WHERE {$condition}");
    $totalfee = db_fetchcolumn ( 'SELECT sum(cm.fee) FROM ' . tablename (t_comm) . " as cm left join ".tablename(t_record)." as d on d.id = cm.recordid
                                        left join ".tablename(t_fans)." as f on f.openid = cm.openid and f.themeid = cm.themeid 
                                        WHERE {$condition}");

    $gsumall = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}'  and status  = 1 and type <> 99" )));
    $gsum0 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 0  and status  = 1 " )));
    $gsum1 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 1  and status  = 1 " )));
    $gsum9 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 9 and status  = 1 " )));
    $gsum2 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 2 and status  = 1 " )));  
    $gsum3 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 3 and status  = 1 " )));  
    $gsum4 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 4 and status  = 1 " )));  
    $gsum5 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 5 and status  = 1 " )));  
    $gsum6 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 6 and status  = 1 " )));  
    $gsum7 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 7 and status  = 1 " )));  
    $gsum11 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 7 and status  = 1 " )));  
    $gsum99 = sprintf("%.2f",floatval(db_fetchcolumn ( 'SELECT sum(fee) FROM ' . tablename ( t_comm ) . "
            WHERE themeid ='{$themeid}' and type = 99 and status  = 99 " )));  


	$pager = pagination ( $total, $pageNumber, $pageSize );

    if($status == -2){
        $workerid = '';
        $type = -1;
        $keyword='';

        $sql = "SELECT * FROM ".tablename(t_fans)." 
                WHERE themeid =" . $themeid . " and feesum >0 order by feesum desc
                      LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;
        $list = db_select ( $sql);

        $totalpaihang = db_fetchcolumn ( "SELECT COUNT(*) FROM ".tablename(t_fans)." 
                WHERE commcount >0");
        $pager = pagination ( $totalpaihang, $pageNumber, $pageSize );
    }elseif($status == -3){
        $workerurl = createWebUrl('commshare', array('op' => 'display','themeid'=>$themeid));
        echo "<script language='javascript' type='text/javascript'>";
        echo "window.location.href='$workerurl';"; 
        echo "</script>";  
        exit;
    }
	
}

if($op == 'inputlist') {
    
    $pageNumber = max ( 1, intval ( $_P['page'] ) );

    $pageSize = intval ( $_P['pageSize'] );
    if ($pageSize<1){
        $pageSize = 10;
    }

    $moduleslist = db_select('SELECT name FROM ' . tablename('modules') . " order by mid desc LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize );
    $total  =db_fetchcolumn ( "SELECT COUNT(*) FROM ".tablename('modules'));

    foreach ($moduleslist as $index => $item) {
        $softtable = $item['name']."_acomm";
        $sql = "SHOW TABLES LIKE '". str_replace("`", "", tablename($softtable))  ."'" ;
        $result = db_find($sql);
        $softtotal = 0;
        $successcnt = 0 ;
        $errorcnt = 0 ;
        $issoft = '否';
        if ($result !== false ){
            $issoft = '是';
            $sql = 'SELECT uniacid,ordersn,themeid,recordid,type,openid,uid,fee,addtime,sendtime,status,fromuid,fopenid,workerid,city,ip,msg FROM ' . tablename($softtable) . ' WHERE type = 4 or type = 7 order by id';
            $commlist = db_select($sql);
            $softtotal = db_fetchcolumn ( 'SELECT COUNT(*) FROM ' . tablename($item['name']."_acomm") . ' WHERE type = 4 or type = 7 ');

            $isinput = db_find ( "SELECT * FROM " . tablename ( '2019comm_list' ) . " WHERE software = '" . $item['name'] . "'");
            if (empty($isinput)) {
                foreach ($commlist as $commindex => $commitem) {
                    $commitem['software'] = $item['name'];

                        $r = $insertid = db_insert('2019comm_list', $commitem);
                        if(!empty($r)){
                            $successcnt= $successcnt+1;
                        }else{
                            $errorcnt= $errorcnt+1;
                        }
                }
            }else{
                $issoft = '重复';
            }
        }
        $moduleslist[$index]['issoft'] =$issoft;
        $moduleslist[$index]['num'] =$softtotal;
        $moduleslist[$index]['successcnt'] = $successcnt;
        $moduleslist[$index]['errorcnt'] = $errorcnt;
    }
    $pager = pagination ( $total, $pageNumber, $pageSize );
    $return_clicent = get_defined_vars();
return view('/inputlist' , $return_clicent);
    exit;
}

if($op == 'delete') {
	db_delete(t_comm, array('id' => $id,'themeid'=>$themeid));
	return_msg('删除成功！', $url, 'success');
}
if($op == 'hand'){

    $comm = db_find ( "SELECT * FROM ".tablename(t_comm)." WHERE id ='{$id}'" );
    $r = Fee::commHand($comm,$system);
    if($r[0]=="0"){
        return_tips($r[1], $url, 'success');
    }else{
        return_tips($r[1]);
    }

}

if($op == 'check'){
    if ($system['autored']<2 || ($system['autored']==2 && $row['type'] == 99)){
        $totalpayfee = Order::getRealByThemeIdnew($themeid) + $theme['chongzhi'];
        if ($totalpayfee<1){
            return_msg('您的余额不足,无法退款,需先充值再补发');
        }
    	$comm = db_find ( "SELECT * FROM ".tablename(t_comm)." WHERE id ='{$id}'" );
        if ($comm['type']==10 || $comm['type']==11) {
            return_msg('此类红包不可补发');
        }
        $r = Fee::commRecord($comm,$system);
        if($r[0]=="0"){
            return_tips($r[1], $url, 'success');
        }else{
            return_tips($r[1]);
        }
    }else{
        return_msg("无权操作");
    }

}
$return_clicent = get_defined_vars();
return view('/comm' , $return_clicent);
}
}